import tkinter as tk


class TopmostWindow:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("置顶窗口示例")
        self.is_topmost = tk.BooleanVar(value=True)
        self.root.attributes('-topmost', self.is_topmost.get())

        self.btn_toggle = tk.Button(
            self.root,
            text="取消置顶",
            command=self.toggle_topmost,
            font=('微软雅黑', 8),  # 减小字体大小
            width=8,  # 设置按钮宽度
            height=1  # 设置按钮高度
        )
        # 使用 place 布局将按钮放在最右边
        self.btn_toggle.place(relx=1, rely=0.5, anchor='e', x=-10)

        self.is_topmost.trace_add('write', self.update_button_text)

    def toggle_topmost(self):
        new_state = not self.is_topmost.get()
        self.is_topmost.set(new_state)
        self.root.attributes('-topmost', new_state)

    def update_button_text(self, *args):
        self.btn_toggle.config(
            text=f"{'取消置顶' if self.is_topmost.get() else '启用置顶'}"
        )

    def run(self):
        self.root.mainloop()


if __name__ == '__main__':
    app = TopmostWindow()
    app.run()
